/*============================================================================
 PROJECT: DealHits
 FILE:    PhotoGalleryCell.m
 AUTHOR:  Khoai Nguyen Minh
 DATE:    9/19/13
 =============================================================================*/

/*============================================================================
 IMPORT
 =============================================================================*/
#import "PhotoGalleryCell.h"
#import "AssetLibraryHelper.h"
#import "FFCircularProgressView.h"
#import "FileRequestQueueManager.h"

/*============================================================================
 PRIVATE MACRO
 =============================================================================*/
#define kPhotoGalleryDeleteButtonHeight (IS_IPAD ? 52 : 25)
#define kPhotoGalleryDeleteButtonPadding (IS_IPAD ? 20 : 10)

/*============================================================================
 PRIVATE INTERFACE
 =============================================================================*/

@interface PhotoGalleryCell()
@property (strong, nonatomic) UIImageView   *placeHolderView;
@property (strong, nonatomic) FFCircularProgressView *cicleProgressView;
@property (strong, nonatomic) FileRequestBlock requestBlock;
@end

@implementation PhotoGalleryCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.placeHolderView = [[UIImageView alloc] initWithFrame:self.bounds];
        self.placeHolderView.contentMode = UIViewContentModeScaleAspectFit;
        self.placeHolderView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        self.placeHolderView.backgroundColor = [UIColor blackColor];
        self.placeHolderView.image = [[IBHelper sharedUIHelper] loadCommonImage:@"default_place"];
        [self.contentView addSubview:self.placeHolderView];
        
        self.transform = CGAffineTransformMakeRotation(M_PI_2);
        
        self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.deleteButton setImage:[[IBHelper sharedUIHelper] loadImage:@"icon_delete"] forState:UIControlStateNormal];
        [self.deleteButton addTarget:self action:@selector(didTouchedOnDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:self.deleteButton];
        
        /* add cicle progress view here */
        self.cicleProgressView = [[FFCircularProgressView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        self.cicleProgressView.progressType = kProgressTypeUpload;
        self.cicleProgressView.hidden = YES;
        [self.contentView addSubview:self.cicleProgressView];
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.deleteButton.frame = CGRectMake(self.bounds.size.width - kPhotoGalleryDeleteButtonHeight - kPhotoGalleryDeleteButtonPadding, kPhotoGalleryDeleteButtonPadding, kPhotoGalleryDeleteButtonHeight, kPhotoGalleryDeleteButtonHeight);
    self.cicleProgressView.center = self.contentView.center;
}

- (void)loadOriginalImageOfThumbnail:(UIImage *)placeHolder {
    __weak PhotoGalleryCell *weakSelf = self;
    [_placeHolderView setImageWithURLString:self.request.url
                           placeholderImage:placeHolder
                                    success:^(UIImage *image) {
                                        weakSelf.placeHolderView.image = image;
                                        [weakSelf.placeHolderView stopLoading];
                                    }
                                    failure:^(NSError *error) {
                                        [weakSelf.placeHolderView stopLoading];
                                    }];
}

- (void)setRequest:(FileRequest *)request {
    _request = request;
    
    /* load default cover image */
    _placeHolderView.image = [[IBHelper sharedUIHelper] loadImage:@"default_place"];
    if(self.request.url.length > 0) { /* start cicle progress here */
        if([self.request.url hasPrefix:kAssetURLFormat]) {
            FileRequestQueueManager *manager = [FileRequestQueueManager sharedManager];
            self.cicleProgressView.hidden = NO;
            
            if([manager isUploadingFileRequest:self.request]) {
                [self.cicleProgressView startSpinProgressBackgroundLayer];
            }
            
            /* create request file block */
            if(!self.requestBlock) {
                __weak PhotoGalleryCell *weakSelf = self;
                self.requestBlock = ^(FileRequest *fileRequest, CGFloat percentage, NSError *error) {
                    if([fileRequest.identifier isEqualToString:weakSelf.request.identifier]) {
                        if(percentage > 0 && percentage < 1) {
                            weakSelf.cicleProgressView.progress = percentage;
                            
                            if(weakSelf.cicleProgressView.isSpinning) {
                                [weakSelf.cicleProgressView stopSpinProgressBackgroundLayer];
                            }
                        } else if (percentage == 1 || error) {
                            weakSelf.cicleProgressView.hidden = YES;
                        }
                    }
                };
            }
            
            /* add photo into upload queue */
            [manager uploadFile:self.request
                     usingBlock:self.requestBlock];
            
            [self.placeHolderView startLoading];
            [[AssetLibraryHelper sharedPhotoLibraryAccessor] getAssestByURL:self.request.url
                                                                resultBlock:^(ALAsset *asset, NSError *error) {
                                                                    _placeHolderView.image = [asset originalImage];
                                                                    [self.placeHolderView stopLoading];
                                                                }];
        } else {
            self.cicleProgressView.hidden = YES;
            [self.placeHolderView startLoading];
            [self loadOriginalImageOfThumbnail:[[IBHelper sharedUIHelper] loadImage:@"default_place"]];
            
        }
    }
}

- (void)didTouchedOnDeleteButton:(UIButton *)sender {
    if(_callback != NULL) {
        _callback(self);
    }
}

@end
